package com.training.jsp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ProductController", value = "/jsp/products")
public class ProductController extends HttpServlet {
    // 内存数据存储 (替代数据库)
    private static final List<Map<String, Object>> products = new ArrayList<>();

    static {
        // 初始化商品数据
        products.add(createProduct(1, "Laptop", 999.99, 10));
        products.add(createProduct(2, "Smartphone", 699.99, 15));
        products.add(createProduct(3, "Tablet", 399.99, 20));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 1. 业务逻辑：获取所有商品
        List<Map<String, Object>> allProducts = getAllProducts();

        // 2. 设置视图数据
        request.setAttribute("products", allProducts);
        request.setAttribute("pageTitle", "Product List");

        // 3. 转发到JSP视图
        request.getRequestDispatcher("/WEB-INF/views/products.jsp").forward(request, response);
    }

    public List<Map<String, Object>> getAllProducts() {
        // 所有逻辑都在Controller中处理
        return new ArrayList<>(products);
    }

    // 创建商品数据的辅助方法
    private static Map<String, Object> createProduct(int id, String name, double price, int stock) {
        Map<String, Object> product = new HashMap<>();
        product.put("id", id);
        product.put("name", name);
        product.put("price", price);
        product.put("stock", stock);
        return product;
    }
}
